package com.link.wseller.controller;

import com.link.wseller.domain.ProductCategory;
import com.link.wseller.domain.ProductInfo;
import com.link.wseller.http.JsonResult;
import com.link.wseller.serive.ProductCategoryService;
import com.link.wseller.serive.ProductInfoSerivce;
import com.link.wseller.serive.impl.ProductCategoryServiceImpl;
import com.link.wseller.serive.impl.ProductInfoServiceImpl;
import com.link.wseller.vo.ProductInfoVo;
import com.link.wseller.vo.ProductVo;
import javafx.print.Collation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.text.CollatorUtilities;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductCategoryServiceImpl categoryService;

    @Autowired
    private ProductInfoServiceImpl productInfoSerivce;


    @GetMapping("list")
    public JsonResult getProductList(){

        //查询所有上架的商品
        List<ProductInfo> productInfoList = productInfoSerivce.findUpAll();

        //查询所有的类目
        List<Integer> categoryTypeList = productInfoList.stream()
                .map(e -> e.getCategoryType())
                .collect(Collectors.toList());

        List<ProductCategory> categoryList = categoryService.findByCategoryTypeIn(categoryTypeList);

        //瓶装数据
        List<ProductVo> productVOList = new ArrayList<>();

        for (ProductCategory category: categoryList){

            ProductVo productVo = new ProductVo();
            productVo.setCategoryName(category.getCategoryName());
            productVo.setCategoryType(category.getCategoryType());

            List<ProductInfoVo> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo: productInfoList){
                if (productInfo.getCategoryType().equals(category.getCategoryType())){
                    ProductInfoVo productInfoVo = new ProductInfoVo();
                    BeanUtils.copyProperties(productInfo, productInfoVo);
                    productInfoVOList.add(productInfoVo);
                }
            }

            productVo.setProductInfoVoList(productInfoVOList);
            productVOList.add(productVo);
        }

        if (!CollectionUtils.isEmpty(productVOList)){
            return JsonResult.created(productVOList);
        }

        return JsonResult.error("获取数据失败");
    }

}
